<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="800" @ok="handleSubmit">
      <BasicForm @register="registerForm"/>
  </BasicModal>
</template>

<script lang="ts" setup>
    import {ref, computed, unref} from 'vue';
    import {defHttp} from '/@/utils/http/axios';
    import {BasicModal, useModalInner} from '/@/components/Modal';
    import {BasicForm, useForm} from '/@/components/Form/index';
    import {formSchema} from '../WebSchoolMessage.data';
    import {saveOrUpdate,webWorkFileList} from '../WebSchoolMessage.api';
    // Emits声明
    const emit = defineEmits(['register','success']);
    const isUpdate = ref(true);
    const isDetail = ref(false);
    //表单配置
    const [registerForm, {setProps,resetFields, setFieldsValue, validate}] = useForm({
        //labelWidth: 150,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: {span: 24}
    });
    //表单赋值
    const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
        //重置表单
        await resetFields();
        setModalProps({confirmLoading: false,showCancelBtn:!!data?.showFooter,showOkBtn:!!data?.showFooter});
        isUpdate.value = !!data?.isUpdate;
        isDetail.value = !!data?.showFooter;
        if (unref(isUpdate)) {
            //表单赋值
            await setFieldsValue({
                ...data.record,
            });
            initFormData(data.record.id);
        }
        // 隐藏底部时禁用整个表单
       setProps({ disabled: !data?.showFooter })
    });
    //设置标题
    const title = computed(() => (!unref(isUpdate) ? '新增' : !unref(isDetail) ? '详情' : '编辑'));
    const originalFiles = ref([]); // 新增变量来存储原始附件列表
    //表单提交事件
    async function handleSubmit(v) {
      try {
        let values = await validate();
        setModalProps({ confirmLoading: true });
    
        // 确保 files 和 imagefiles 是字符串，如果未定义则初始化为空字符串
        const files = values['files'] || '';
        const imagefiles = values['imagefiles'] || '';
    
        // 获取当前表单中的附件列表
        const currentFiles = files.split(',').filter(Boolean);
        const currentImageFiles = imagefiles.split(',').filter(Boolean);
    
        // 获取需要删除的附件列表
        const deletedFiles = originalFiles.value.filter(file => !currentFiles.includes(file));
        const deletedImageFiles = originalFiles.value.filter(file => !currentImageFiles.includes(file));
    
        // 发送删除请求
        await Promise.allSettled([
          ...deletedFiles.map(file => deleteFile(file.id)),
          ...deletedImageFiles.map(file => deleteFile(file.id)),
        ]);
    
        // 准备提交的数据
        const fileList = [];
        currentFiles.forEach(file => fileList.push({ "filePath": file, "fileName": file }));
        currentImageFiles.forEach(file => fileList.push({ "filePath": file, "fileName": file, "fileType": "PNG" }));
        values['webWorkFileList'] = fileList;
    
        // 提交表单
        await saveOrUpdate(values, isUpdate.value);
    
        // 关闭弹窗
        closeModal();
    
        // 刷新列表
        emit('success');
      } catch (error) {
        console.error('提交失败:', error);
      } finally {
        setModalProps({ confirmLoading: false });
      }
    }

   async function initFormData(_id) {
     let params = { id: _id };
     const data = await defHttp.get({ url: webWorkFileList, params });
     const nonPngFiles = [];
     const pngFiles = [];
     
     for (let i = 0; i < data.length; i++) {
       if (data[i]['fileType'] === 'PNG') {
         pngFiles.push(data[i]['filePath']);
       } else {
         nonPngFiles.push(data[i]['filePath']);
       }
     }
     
     await setFieldsValue({ 'files': nonPngFiles.join(',') });
     await setFieldsValue({ 'imagefiles': pngFiles.join(',') });
   }
    // 删除附件的函数
   async function deleteFile(fileId) {
     try {
       await defHttp.post({
         url: '/website/webWorkFile/delete', // 使用完整的 URL 路径
         params: { id: fileId },
       });
       console.log('附件删除成功:', fileId);
     } catch (error) {
       console.error('删除附件失败:', error);
       throw error; // 重新抛出错误，以便在 handleSubmit 中处理
     }
   }
</script>

<style lang="less" scoped>
	/** 时间和数字输入框样式 */
  :deep(.ant-input-number) {
    width: 100%;
  }

  :deep(.ant-calendar-picker) {
    width: 100%;
  }
</style>
